package org.unisannio.remoteproxy;

import it.unipr.ce.dsg.s2p.sip.Address;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

import org.unisannio.remote.BroadcastContentPeer;
import org.unisannio.remote.FactoryRemote;
import org.unisannio.remote.Proxy;
import org.unisannio.remote.RemoteActivity;
import org.unisannio.util.Converter;
import org.unisannio.util.ServiceInfo;
import org.unisannio.util.TransferManager;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class RemoteProxy extends Proxy implements OnItemSelectedListener {

	public static RemoteActivity remoteActivity;
	public String URI = "android.media.action.IMAGE_CAPTURE";
	Button richiedi;
	private RelativeLayout layout;
	private String TAG = "RemoteProxyActivity";
	private static HashMap<Integer, Bundle> biggestMap = new HashMap<Integer, Bundle>();
	Integer code;
	private Spinner spinner;
	private ArrayList<Address> indirizzi = new ArrayList<Address>();
	private ArrayAdapter<Address> adapter;
	int i = 0;
	private static Intent reqIntent = null;
	private static int reqCode = 0;
	private Intent originalIntent = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// biggestMap=new HashMap<Integer, Bundle>();
		code = 0;

		setContentView(R.layout.activity_remote);
		// URI=getIntent().getAction();

		Button bPubblicati = (Button) findViewById(R.id.bPubblicati);
		bPubblicati.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				SharedPreferences prefs = PreferenceManager
						.getDefaultSharedPreferences(RemoteProxy.this);
				String ip = prefs.getString("myschoolserverIp", "");
				String port = prefs.getString("myschoolserverPort", "");
				String ipSuper = prefs.getString("superPeerIp", "");
				String portSuper = prefs.getString("superPeerPort", "");
				
				
				FactoryRemote factoryRemote = new FactoryRemote();
				remoteActivity = factoryRemote
						.getRemoteActivity(RemoteProxy.this);
				remoteActivity.setServer("superPeer@"+ipSuper+":"+portSuper);
				ServiceInfo sinfo = new ServiceInfo();
				sinfo.addDescriptor(URI, null, null,
						ServiceInfo.REMOTE_ACTIVITY);
				remoteActivity.sendToSuperPeer(sinfo, Converter.PUBLISH);
				remoteActivity.sendToSuperPeer(sinfo, Converter.SUBSCRIBE);
				indirizzi = remoteActivity.retrieveAvailableAddress(URI);
				TransferManager.setImageServerIP(ip);
				TransferManager.setImageServerPORT(port);
			}
		});

		spinner = (Spinner) findViewById(R.id.sFriends);

		adapter = new ArrayAdapter<Address>(this,
				android.R.layout.simple_spinner_item, indirizzi);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		spinner.setOnItemSelectedListener(this);

		ImageButton refresh = (ImageButton) findViewById(R.id.refresh);
		refresh.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				indirizzi = remoteActivity.retrieveAvailableAddress(URI);
				adapter = new ArrayAdapter<Address>(RemoteProxy.this,
						android.R.layout.simple_spinner_item, indirizzi);
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				spinner.setAdapter(adapter);
			}
		});

		richiedi = (Button) findViewById(R.id.bRichiedi);
		richiedi.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = getIntent();
				Bundle extras = i.getExtras();
				boolean ok = false;
				if (extras == null) {
					if (originalIntent == null) {
						Toast.makeText(RemoteProxy.this,
								"Action non valida per richiesta foto",
								Toast.LENGTH_SHORT).show();
						finish();
					} else {
						i = originalIntent;
						extras = i.getExtras();
						ok = true;
					}
				} else {
					if (extras.get(MediaStore.EXTRA_OUTPUT) != null) {
						originalIntent = (Intent) i.clone();
						ok = true;
					} else {
						finish();
					}
				}
				if (ok) {
					String filePath;
					try{
						Uri fileUri = (Uri) extras.get(MediaStore.EXTRA_OUTPUT);
						filePath = fileUri.getPath();
					}
					catch (ClassCastException e) {
						filePath = (String) extras.get(MediaStore.EXTRA_OUTPUT);
					}
					i.putExtra(MediaStore.EXTRA_OUTPUT, filePath);
					remoteActivity.startActivityForResult(i, 7258);
				}
			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.activity_remote, menu);
		return result;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_settings:
			this.startActivity(new Intent(this, PrefsActivity.class));
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		data = new Intent();
		File file = new File(getExternalFilesDir(null),
				BroadcastContentPeer.PICTURE_IMAGE);
		data.setDataAndType(Uri.parse(file.getAbsolutePath()), "image/jpg");

		remoteActivity.returnActivityResult(requestCode, resultCode, data);

		// super.onActivityResult(requestCode, resultCode, data);
		// // System.out.println(data.getExtras());
		// // String filename = data.getStringExtra(MediaStore.EXTRA_OUTPUT);
		// // System.out.println(filename);
		//
		// Intent i = new Intent();
		// i.setAction("android.media.action.IMAGE_CAPTURE.personal");
		// File image = new File(getExternalFilesDir(null), "test.jpg");
		// String sourceFileUri = image.getAbsolutePath();
		//
		// // Intent intent = new Intent(this, ViewActivity.class);
		// // intent.setData(Uri.parse(sourceFileUri));
		// i.setDataAndType(Uri.parse(sourceFileUri), "image/jpg");
		// // broadcaster.returnRemoteResult(i.getAction(),
		// biggestMap.get(requestCode));
		// // remoteActivity.returnRemoteResult(i, biggestMap.get(requestCode));
		// // broadcaster.sendRemoteOrderedBroadcast(i, null, null, null, 0,
		// null,new Bundle());
		// // Intent i = new Intent(this, FaceRecognitionActivity.class);
		// // i.putExtra(FaceRecognitionActivity.CAPTURED, resultCode);
		// // startActivity(i);
	}

	public void showImage(String remoteFilename) {
		if (remoteFilename != null) {
			// TransferManager.downloadFromServer("http://10.0.2.2:8080/swap/"
			// + remoteFilename, getExternalFilesDir(null)
			// .getAbsolutePath());
			layout = new RelativeLayout(this);
			String pathName = getExternalFilesDir(null).getAbsolutePath()
					+ File.separator + remoteFilename;

			ImageView imView = new ImageView(this);
			imView.setImageBitmap(this.getBitmap(pathName));
			// imView.setImageURI(Uri.parse(getExternalFilesDir(null).getAbsolutePath()+File.separator+remoteFilename));

			layout.addView(imView);
			this.setContentView(layout);

		}

	}

	private Bitmap getBitmap(String path) {
		// Uri uri = Uri.parse(path);
		InputStream in = null;
		try {
			final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
			in = new FileInputStream(new File(path));
			// in = mContentResolver.openInputStream(uri);

			// Decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(in, null, o);
			in.close();

			int scale = 1;
			while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) > IMAGE_MAX_SIZE) {
				scale++;
			}
			Log.d(TAG, "scale = " + scale + ", orig-width: " + o.outWidth
					+ ",  orig-height: " + o.outHeight);

			Bitmap b = null;
			in = new FileInputStream(new File(path));
			if (scale > 1) {
				scale--;
				// scale to max possible inSampleSize that still yields an image
				// larger than target
				o = new BitmapFactory.Options();
				o.inSampleSize = scale;
				b = BitmapFactory.decodeStream(in, null, o);

				// resize to desired dimensions
				int height = b.getHeight();
				int width = b.getWidth();
				Log.d(TAG, "1th scale operation dimenions - width: " + width
						+ ",  height: " + height);

				double y = Math.sqrt(IMAGE_MAX_SIZE
						/ (((double) width) / height));
				double x = (y / height) * width;

				Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
						(int) y, true);
				b.recycle();
				b = scaledBitmap;

				System.gc();
			} else {
				b = BitmapFactory.decodeStream(in);
			}
			in.close();

			Log.d(TAG, "bitmap size - width: " + b.getWidth() + ", height: "
					+ b.getHeight());
			return b;
		} catch (IOException e) {
			Log.e(TAG, e.getMessage(), e);
			return null;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	public Integer addSender(Bundle originalBundle) {
		code += 1;
		biggestMap.put(code, originalBundle);
		return code;
	}

	@Override
	public void onRemoteActivityResult(int reqCode, int resCode, Intent data) {
		super.onActivityResult(reqCode, resCode, data);
//		Toast.makeText(this.getApplicationContext(), "Immagine ricevuta", Toast.LENGTH_LONG).show();
		if (super.getParent() == null) {
			Log.d(TAG,"NO PARENT");
			super.setResult(RESULT_OK, data);
		} else {
			super.getParent().setResult(RESULT_OK, data);
			Log.d(TAG,"PARENT ALREADY SET");
		}
		finish();
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int pos,
			long id) {
		ArrayList<Address> address = new ArrayList<Address>();
		address.add(adapter.getItem(pos));
		RemoteProxy.remoteActivity.saveChosenAddress(address);
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {

	}

	@Override
	protected void onResume() {
		if (reqIntent != null) {
			startActivityForResult(reqIntent, reqCode);
			reqIntent = null;
			reqCode = 0;
		}

		TextView tv = (TextView) findViewById(R.id.helloWorld);
		tv.setText("OnResume " + (i++));
		super.onResume();
	}

	@Override
	public void storeRequestIntent(Intent intent, int requestCode) {
		reqIntent = intent;
		reqCode = requestCode;
	}

}
